In this recipe we explore a new way of doing script flow control with JavaScript 1.2.Discussion
How many times have you had to write something like the following piece of script?if(inVar == 'Aardvark') outVar = '1'; else if(inVar == 'Bat') outVar = '2'; else if(inVar == 'Crocodile') outVar = '3'; else outVar = '0';It's not a very attractive style of script writing (although often necessary), and tends to march off the editing window if you indent everything to preserve the structure. This can make for hard-to-read scripts.
The JavaScript 1.2 standard offers something more friendly and readable, the switch() function:
switch(inVar) { case 'Aardvark': outVar = 1; break; case 'Bat': outVar = 2; break; case 'Crocodile': outVar = 3; break; default: outVar = 0; }The switch() function compares the value of its variable argument to the case labels inside the body of the switch, and executes whatever script code is associated with the matching label. You might miss some subtleties of this function at first glance:
- An arbitrary case value can appear only once, but values can be written into the switch() in any order you choose.
- Execution will fall from one case to the next unless interrupted by the break keyword. This can be used to great advantage for some scripting purposes (see the next bullet item).
- You can't write case "Dog" | "Cat":, but you can put multiple case labels together for one piece of script:
switch(animal) { case 'Cat': case 'Rat': case 'Elephant': aniType = 'mammal'; break; case 'Turtle': case 'Crocodile': case 'Alligator': aniType = 'reptile'; break; case 'Unicorn': aniType = 'mythical'; break; default: aniType = 'unknown'; }- The default label is always the last case label, if used. If you don't use a default label, and the switch argument value doesn't match any of the case labels, then no script code is executed and the script continues on with the first statement following the switch().
Copyright ©2000 by Charles River Media, All Rights Reserved